<template>
  <div class="middle">
    <div class="area-selector-container">
      <el-cascader
        v-model="selectedValue"
        :options="areaOptions"
        placeholder="请选择区域/空间"
        clearable
        :props="cascaderProps"
        @change="handleChange"
      />
    </div>
    <div class="area-button">
      <!-- <el-button
        v-if="selectedValue && selectedValue.length > 1"
        type="primary" 
        plain 
        @click="handleEnergyTrendClick"
      >能耗趋势</el-button> -->
    </div>
    <EnergyTrendDialog  ref="energyTrendDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getBuildingList, getSpaceList } from '@/views/setting/building/api/building.api'
import EnergyTrendDialog from './EnergyTrendDialog.vue'

interface Space {
  id: string | number;
  name: string;
  ossId?: string | number;
}

interface Area {
  id: string | number;
  name: string;
  spaces: Space[];
}

// 级联选择器配置
const cascaderProps = {
  value: 'id',       // 指定选项的值为选项对象的 id 属性值
  label: 'name',     // 指定选项标签为选项对象的 name 属性值
  children: 'spaces', // 指定选项的子选项为选项对象的 spaces 属性值
  checkStrictly: false, // 是否严格的遵守父子节点不互相关联
  emitPath: true     // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组
}

const selectedValue = ref<(string | number)[]>([]) // 存储选中的值
const areaOptions = ref<Area[]>([]) // 存储区域和空间数据
const allSpaces = ref<Map<string | number, Space>>(new Map()) // 存储所有空间信息

const energyTrendDialogRef = ref() 

const emit = defineEmits(['space-selected'])

const handleChange = (value: (string | number)[]) => {
  if (value && value.length > 1) {
    // 最后一个值是空间ID
    const spaceId = value[value.length - 1]
    const space = allSpaces.value.get(spaceId)
    
    if (space) {
      emit('space-selected', space)
    }
  } else {
    emit('space-selected', null)
  }
}

const handleEnergyTrendClick = () => {
  if (!selectedValue.value || selectedValue.value.length <= 1) {
    ElMessage.warning('请先选择空间')
    return
  }
  const spaceId = selectedValue.value[selectedValue.value.length - 1]
  energyTrendDialogRef.value?.openDialog(spaceId)
}

// 获取区域和空间数据
const fetchAreaData = async () => {
  try {
    // 调用获取区域列表的API
    const res = await getBuildingList({})
    
    if (res && res.code === 200 && res.data) {
      // 处理响应数据，为每个区域加载对应的空间列表
      const areas = res.data || []
      const areasWithSpaces: Area[] = []
      
      // 清空之前的空间Map
      allSpaces.value.clear()
      
      // 遍历区域列表，为每个区域加载空间
      for (const area of areas) {
        // 获取该区域下的空间列表
        const spacesRes = await getSpaceList(area.id)
        const spaces = spacesRes.data || []
        
        // 收集所有空间信息
        const spacesList = spaces.map(space => {
          const spaceData = {
            id: space.id,
            name: space.name,
            ossId: space.ossId
          }
          // 将空间添加到Map中，方便后续查找
          allSpaces.value.set(space.id, spaceData)
          return spaceData
        })
        
        // 构建级联选择器数据结构
        areasWithSpaces.push({
          id: area.id,
          name: area.name,
          spaces: spacesList
        })
      }
      
      areaOptions.value = areasWithSpaces

      // 默认选中第一个区域的第一个空间
      if (areasWithSpaces.length > 0 && areasWithSpaces[0].spaces.length > 0) {
        const firstArea = areasWithSpaces[0]
        const firstSpace = firstArea.spaces[0]
        selectedValue.value = [firstArea.id, firstSpace.id]
        // 触发选择事件
        handleChange(selectedValue.value)
      }
    }
  } catch (error) {
    console.error('获取区域数据失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAreaData()
})
</script>

<style lang="scss" scoped>
.middle {
  width: calc(100% - 46.4583%);
  padding: 1.2% 0;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.area-selector-container {
  position: absolute;
  left: 15px;
  z-index: 10;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .el-cascader {
    width: 240px;
  }
}

.area-button {
  position: absolute;
  left: 15px;
  bottom: 15px;
  z-index: 10;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
